<template>
  <div class="app-container">
    <div class="filter-container">
      <div>
        <el-input
          v-model="listQuery.nick_name"
          clearable
          placeholder="用户名"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          @clear="handleFilter"
        />
        <el-input
          v-model="listQuery.title"
          clearable
          placeholder="标题"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          @clear="handleFilter"
        />
        <el-input
          v-model="listQuery.order_no"
          clearable
          placeholder="订单编号"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          @clear="handleFilter"
        />
        <el-input
          v-model="listQuery.out_order_no"
          clearable
          placeholder="订单退款编号"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
          @clear="handleFilter"
        />
        <el-select
          v-model="listQuery.type"
          clearable
          placeholder="订单类型"
          style="width: 130px"
          class="filter-item"
          @change="handleFilter"
        >
          <el-option label="赞赏" :value="1" />
          <el-option label="图鸟小商店" :value="2" />
        </el-select>
        <el-select
          v-model="listQuery.status"
          clearable
          placeholder="订单状态"
          style="width: 130px"
          class="filter-item"
          @change="handleFilter"
        >
          <el-option v-for="(item, index) in order_status" :key="'order_status_query' + index" :label="item.label" :value="item.value" />
        </el-select>
        <el-button
          v-waves
          style="margin-left: 10px"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >
          搜索
        </el-button>
        <el-button
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          @click="handleDelete(0)"
        >
          批量删除
        </el-button>
      </div>
      <div>
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="downloadAllOrderData"
        >
          下载全部订单数据
        </el-button>
        <el-button
          v-waves
          style="margin-left: 10px"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="downloadDeliveryOrderData"
        >
          下载待发货订单数据
        </el-button>
        <el-button
          v-waves
          style="margin-left: 10px"
          class="filter-item"
          type="primary"
          icon="el-icon-upload2"
        >
          上传订单发货数据
        </el-button>
      </div>
    </div>

    <el-table
      ref="itemDataTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top: 20px"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="ID"
        prop="id"
        align="center"
        width="80"
      />
      <el-table-column label="主图" width="80" align="center">
        <template slot-scope="{ row: { img_url: { prefix } }}">
          <img
            v-if="prefix === ''"
            style="width: 50px"
            src="@/assets/static/image/noImg.png"
          >
          <a v-else :href="prefix" target="_blank">
            <img
              :src="prefix"
              style="width: 50px"
            >
          </a>
        </template>
      </el-table-column>
      <el-table-column label="订单标题" align="center">
        <template slot-scope="{ row: { titleWrapper }}">
          <span v-html="titleWrapper" />
        </template>
      </el-table-column>
      <el-table-column label="订单编号" align="center">
        <template slot-scope="{ row: { order_noWrapper }}">
          <span v-html="order_noWrapper" />
        </template>
      </el-table-column>
      <el-table-column label="退款编号" align="center">
        <template slot-scope="{ row: { out_order_noWrapper }}">
          <span v-html="out_order_noWrapper" />
        </template>
      </el-table-column>
      <el-table-column
        label="订单金额"
        prop="amount"
        align="center"
        width="80"
      />
      <el-table-column
        label="退款金额"
        prop="refund_amount"
        align="center"
        width="80"
      />
      <el-table-column label="头像" width="80" align="center">
        <template slot-scope="{ row: { avatar_url }}">
          <img
            v-if="avatar_url === ''"
            style="width: 50px"
            src="@/assets/static/image/noImg.png"
          >
          <a v-else :href="avatar_url" target="_blank">
            <img
              :src="avatar_url"
              style="width: 50px"
            >
          </a>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" width="120">
        <template slot-scope="{ row: { nick_nameWrapper }}">
          <span v-html="nick_nameWrapper" />
        </template>
      </el-table-column>
      <el-table-column label="订单类型" width="150" align="center">
        <template slot-scope="{ row:{ type }}">
          <span v-if="type === 1"><el-tag type="info">赞赏</el-tag></span>
          <span v-if="type === 2"><el-tag type="info">图鸟商店</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="150" align="center">
        <template slot-scope="{ row }">
          <span><el-tag type="info">{{ order_status[row.status - 1].label }}</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" align="center" fixed="right">
        <template slot-scope="{ row: { id, type, status, virtual_product } }">
          <el-button class="order-operation-btn" size="mini" type="primary" icon="el-icon-edit" @click="handleView(id)">查看</el-button>
          <el-button v-if="virtual_product === 0" class="order-operation-btn" :disabled="status | deliveryStatus(type)" size="mini" type="warning" icon="el-icon-truck" @click="handleDelivery(id)">发货</el-button>
          <el-button v-if="virtual_product === 1" class="order-operation-btn" :disabled="status | serveStatus(type)" size="mini" type="warning" icon="el-icon-truck" @click="handleServe(id)">服务</el-button>
          <el-button class="order-operation-btn" :disabled="status | refundStatus(type)" size="mini" type="warning" icon="el-icon-s-release" @click="handleRefund(id)">退款</el-button>
          <el-button class="order-operation-btn" size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="handleFilter"
    />

    <!-- 发起退款弹出框 -->
    <el-dialog
      title="订单退款"
      :visible.sync="dialogRefundVisible"
      :close-on-click-modal="false"
      @close="closeRefundDialog"
    >
      <order-refund-detail v-if="dialogRefundVisible" :id="orderID" ref="orderRefundDetail" @isRefund="handleisRefund" @ended="handleRefundEnd" />
    </el-dialog>

    <!-- 订单详情弹出框 -->
    <el-dialog
      title="订单详情"
      width="80%"
      :visible.sync="dialogViewVisible"
      :close-on-click-modal="false"
      @close="closeViewDialog"
    >
      <order-view-detail v-if="dialogViewVisible" :id="orderID" ref="orderViewDetail" @ended="handleViewEnd" />
    </el-dialog>

    <!-- 商店订单发货弹出框 -->
    <el-dialog
      title="商店订单发货"
      :visible.sync="dialogDeliveryVisible"
      :close-on-click-modal="false"
      @close="closeDeliveryDialog"
    >
      <order-delivery-detail v-if="dialogDeliveryVisible" :id="orderID" ref="orderDeliveryDetail" @ended="handleDeliveryEnd" />
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import OrderRefundDetail from './components/RefundDetail'
import OrderViewDetail from './components/ViewDetail'
import OrderDeliveryDetail from './components/DeliveryDetail'
import { order_status, wrapperKeyword } from '@/utils'
import { getOrderList, getAllOrderDataExcel, getDeliveryOrderDataExcel, shopVirtualProductOrderServe, deleteOrder } from '@/api/order'

export default {
  name: 'OrderList',
  components: { Pagination, OrderViewDetail, OrderRefundDetail, OrderDeliveryDetail },
  directives: { waves },
  filters: {
    refundStatus(status, order_type) {
      if (order_type === 1 && status === 2) {
        return false
      }
      if (order_type === 2 && [7, 10].indexOf(status) !== -1) {
        return false
      }

      return true
    },
    deliveryStatus(status, order_type) {
      if (order_type === 2 && [2, 9].indexOf(status) !== -1) {
        return false
      }

      return true
    },
    serveStatus(status, order_type) {
      if (order_type === 2 && [2].indexOf(status) !== -1) {
        return false
      }
      return true
    }
  },
  data() {
    return {
      order_status: order_status,
      tableKey: 0,
      listLoading: false,
      total: 0,
      list: [],
      listQuery: {
        page: 1,
        limit: 20,
        nick_name: '',
        title: '',
        order_no: '',
        out_order_no: '',
        type: '',
        status: ''
      },
      dialogRefundVisible: false,
      dialogViewVisible: false,
      dialogDeliveryVisible: false,
      orderID: 0
    }
  },
  watch: {
    list(val) {
      val.forEach(order => {
        order.nick_nameWrapper = wrapperKeyword(this.listQuery['nick_name'] || '', order.nick_name)
        order.titleWrapper = wrapperKeyword(this.listQuery['title'] || '', order.title)
        order.order_noWrapper = wrapperKeyword(this.listQuery['order_no'] || '', order.order_no)
        order.out_order_noWrapper = wrapperKeyword(this.listQuery['out_order_no'] || '', order.out_order_no)
      })
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    handleFilter() {
      this.getList()
    },
    handleView(id) {
      this.orderID = id
      this.dialogViewVisible = true
      this.$nextTick().then(() => {
        this.$refs.orderViewDetail.getOrderByID()
      })
    },
    handleDelivery(id) {
      this.orderID = id
      this.dialogDeliveryVisible = true
      this.$nextTick().then(() => {
        this.$refs.orderDeliveryDetail.getOrderByID()
      })
    },
    handleServe(id) {
      this.$confirm('是否已经对用户进行了服务', '服务确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        shopVirtualProductOrderServe({
          id
        }).then((response) => {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.getList()
        }).catch((err) => {
          this.$message({
            message: err.msg,
            type: 'error'
          })
        })
      }).catch(() => {})
    },
    handleRefund(id) {
      this.orderID = id
      this.dialogRefundVisible = true
      this.$nextTick().then(() => {
        this.$refs.orderRefundDetail.getOrderByID()
      })
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该数据，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        // 判断是否为批量删除
        if (id === 0) {
          const _selection = this.$refs.itemDataTable.selection
          // console.log(_selection)
          if (_selection.length === 0) {
            this.$message({
              message: '请选择需要删除的数据',
              type: 'error'
            })
            return
          }
          _selection.forEach((value, index) => {
            ids.push(value.id)
          })
        } else {
          ids.push(id)
        }

        // console.log(ids)

        deleteOrder(ids).then(response => {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.getList()
        })
      }).catch(() => {})
    },
    downloadAllOrderData() {
      const loading = this.$loading({
        lock: true,
        text: '生成Excel中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getAllOrderDataExcel({
        type: 2
      }).then((response) => {
        // console.log(response)
        loading.close()
        // 提取文件名
        const file_name = response.headers['content-disposition'].match(
          /filename="(.*)"/
        )[1]
        // 将二进制流转为blob
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          window.navigator.msSaveBlob(blob, decodeURI(file_name))
        } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          const blobURL = window.URL.createObjectURL(blob)
          // 创建a标签，用于跳转至下载链接
          const tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', decodeURI(file_name))
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 挂载a标签
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          // 释放blob URL地址
          window.URL.revokeObjectURL(blobURL)
        }
      }).catch((err) => {
        console.log(err)
        loading.close()
      })
    },
    downloadDeliveryOrderData() {
      const loading = this.$loading({
        lock: true,
        text: '生成Excel中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getDeliveryOrderDataExcel({
        type: 2
      }).then((response) => {
        // console.log(response)
        loading.close()
        // 提取文件名
        const file_name = response.headers['content-disposition'].match(
          /filename="(.*)"/
        )[1]
        // 将二进制流转为blob
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          window.navigator.msSaveBlob(blob, decodeURI(file_name))
        } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          const blobURL = window.URL.createObjectURL(blob)
          // 创建a标签，用于跳转至下载链接
          const tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', decodeURI(file_name))
          // 兼容：某些浏览器不支持HTML5的download属性
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 挂载a标签
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          // 释放blob URL地址
          window.URL.revokeObjectURL(blobURL)
        }
      }).catch((err) => {
        console.log(err)
        loading.close()
      })
    },
    closeRefundDialog() {
      // this.$refs.orderRefundDetail.toDefault()
      this.orderID = 0
    },
    closeViewDialog() {
      // this.$refs.orderViewDetail.toDefault()
      this.orderID = 0
    },
    closeDeliveryDialog() {
      // this.$refs.orderViewDetail.toDefault()
      this.orderID = 0
    },
    handleisRefund() {
      this.dialogRefundVisible = false
      this.closeRefundDialog()
    },
    handleRefundEnd() {
      this.dialogRefundVisible = false
      this.getList()
    },
    handleViewEnd() {
      this.dialogViewVisible = false
      this.getList()
    },
    handleDeliveryEnd() {
      this.dialogDeliveryVisible = false
      this.getList()
    },
    getList() {
      this.listLoading = true
      getOrderList(this.listQuery).then(response => {
        const {
          total,
          data
        } = response
        this.total = total
        this.list = data
        this.listLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-operation-btn {
  margin-left: 10px;
  margin-top: 5px;
}
</style>
